//
//  LWXRadioPalyController.m
//  EPA
//
//  Created by lanou3g on 16/4/21.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "LWXRadioPalyController.h"
#import "LWXRadioListModel.h"
#import "LWXAVManager.h"
#import "UserinfoManager.h"
#import "LWXDownloadManager.h"
@interface LWXRadioPalyController ()
// 标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
// 封面
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
// 当前时间
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;

// 播放进度
@property (weak, nonatomic) IBOutlet UISlider *rateSlider;
// 总时长
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;

// 计时器
@property (nonatomic, strong) NSTimer *playTimer;
// 开始暂停按钮
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIImageView *bigImageView;

@end

@implementation LWXRadioPalyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"下载" style:(UIBarButtonItemStylePlain) target:self action:@selector(downloadAction)];
    
    self.navigationItem.rightBarButtonItem = item;
    LWXRadioListModel *model = self.radioArray[self.currentIndex];
    
    self.navigationController.navigationBar.translucent = NO;
    self.titleLabel.text = model.title;
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    
    [self.bigImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
//    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
//    effectView.frame = self.view.bounds;
//    
    //设置旋转
    [self setUpRotating];
    
//    [self.bigImageView addSubview:effectView];
    
    [LWXAVManager shareManager].currentIndex = self.currentIndex;
    NSMutableArray *itemArray = [NSMutableArray new];
    for (LWXRadioListModel *model in self.radioArray) {
        NSURL *musicUrl = [NSURL URLWithString:model.playInfoModel.musicUrl];
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:musicUrl];
        [itemArray addObject:item];
    }
    
    //AVPlayerItem数组
    
    [LWXAVManager shareManager].itemArray = itemArray;
    //播放
    [[LWXAVManager shareManager] play];
    
    //创建 timer
    self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    
    // Do any additional setup after loading the view from its nib.
}

// 点击下载
- (void)downloadAction {
    
    if ([UserinfoManager shareManager].auth) {
        
        
        LWXRadioListModel *model = self.radioArray[self.currentIndex];
        [[LWXDownloadManager shareManager]addDownloadTask:model Progress:^(float progress) {
        
            
            
        } Complete:^(NSString *path) {
            
            
        }];
        
        
        
        
    }else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请登录账号" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
        [alertC addAction:alertAction];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertC animated:YES completion:nil];
        });
    }
    
    
}


//设置旋转
- (void)setUpRotating{
    CAKeyframeAnimation *rotAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    CGFloat point = M_PI_4;
    rotAnimation.values = @[@(1 * point),@(2 * point),@(3 * point),@(4 * point),@(5 * point),@(6 * point),@(7 * point),@(8 * point),@(9 * point)];
    rotAnimation.duration = 10;
    rotAnimation.repeatCount = MAXFLOAT;
    self.coverImageView.layer.masksToBounds = YES;
    self.coverImageView.layer.cornerRadius = self.coverImageView.frame.size.width/2;
    [self.coverImageView.layer addAnimation:rotAnimation forKey:@"rotation"];
}



- (void)timerAction {
    
    float current = [LWXAVManager shareManager].player.currentTime.value / [LWXAVManager shareManager].player.currentTime.timescale;
    NSString *currentStr = [NSString stringWithFormat:@"%02ld:%02ld",(NSInteger)current/60,(NSInteger)current%60];
    self.currentLabel.text = currentStr;
    float total = 0;
    if ([LWXAVManager shareManager].player.currentItem.duration.timescale > 0) {
        total = [LWXAVManager shareManager].player.currentItem.duration.value / [LWXAVManager shareManager].player.currentItem.duration.timescale;
    }

    NSString *totalStr = [NSString stringWithFormat:@"%02ld:%02ld",(NSInteger)total/60,(NSInteger)total%60];
    self.totalLabel.text = totalStr;
    
    
    if (total > 0) {
        float rate = current / total;
        self.rateSlider.value = rate;
    }
    
}

// 改变播放进度
- (IBAction)didClickChangeRateAction:(UISlider *)sender {
    //创建 CMTime
    CMTime changeTime =  CMTimeMake(sender.value * [LWXAVManager shareManager].player.currentItem.duration.value, [LWXAVManager shareManager].player.currentItem.duration.timescale);
    // 调整时间
    [[LWXAVManager shareManager].player seekToTime:changeTime];

}


// 上一曲
- (IBAction)didClickPreviousButton:(id)sender {
   
    [[LWXAVManager shareManager] previous];
    // 图片标题
    self.currentIndex--;
    if (self.currentIndex < 0) {
        self.currentIndex = self.radioArray.count - 1;
    }
    LWXRadioListModel *model = self.radioArray[self.currentIndex];
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    self.titleLabel.text = model.title;
    
    [self.playButton setImage: [UIImage imageNamed:@"暂停"] forState:(UIControlStateNormal)];
}

// 开始 暂停
- (IBAction)didClickPlayButton:(id)sender {
    
    if ([LWXAVManager shareManager].player.rate == 0) {
        [[LWXAVManager shareManager] play];
        [sender setImage:[UIImage imageNamed:@"暂停"] forState: UIControlStateNormal];
    }else {
        [[LWXAVManager shareManager] pause];
        [sender setImage:[UIImage imageNamed:@"开始"] forState: UIControlStateNormal];
        
    }
}

// 下一曲
- (IBAction)didClickNextButton:(id)sender {
    [[LWXAVManager shareManager] next];
    // 图片标题
    self.currentIndex++;
    if (self.currentIndex >= self.radioArray.count) {
        self.currentIndex = 0;
    }
    LWXRadioListModel *model = self.radioArray[self.currentIndex];
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    self.titleLabel.text = model.title;
    
    [self.playButton setImage: [UIImage imageNamed:@"暂停"] forState:(UIControlStateNormal)];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
